/**
 * Created with hong.rong
 * Date:2020/07/17
 */

import React, { useEffect, useState } from 'react'
import { Cascader } from 'antd'
import { getListLevel } from '@/services/config/category'
import { CATEGORY_LEVEL } from '@/constant/category'

export default function CategorySelect({ onChange }) {
  const [options, setOptions] = useState([])

  useEffect(() => {
    async function getOptions() {
      const options = await fetchLevelData(CATEGORY_LEVEL.ONE, undefined)
      setOptions(options)
    }
    getOptions()
  }, [])

  /**
   * 获取层级数据
   * @param cateLevel
   * @param pid
   * @returns {Promise<*>}
   */
  const fetchLevelData = async (cateLevel, pid) => {
    const { data = {} } = await getListLevel({ cateLevel, pid })
    if (data && data.code === 0) {
      const list = data.data || []
      return list.map(item => ({
        value: item.cateId,
        label: item.title,
        isLeaf: item.leaf === 0,
        level: cateLevel,
      }))
    }
    return []
  }
  /**
   * 加载子层级数据
   * @param selectedOptions
   */
  const loadData = async selectedOptions => {
    const targetOption = selectedOptions[selectedOptions.length - 1]
    targetOption.loading = true
    const children = await fetchLevelData(
      targetOption.level + 1,
      targetOption.value
    )
    if (children) {
      targetOption.loading = false
      targetOption.children = children
      setOptions([...options])
    }
  }
  return (
    <Cascader
      options={options}
      loadData={loadData}
      onChange={onChange}
      changeOnSelect
    />
  )
}
